<template>
  <div class="selection-management">
    <div class="page-header">
      <h1>选课记录管理</h1>
      <p>查看和管理所有选课记录</p>
    </div>

    <!-- 搜索和筛选 -->
    <el-card class="search-card">
      <el-form :model="searchForm" @submit.prevent="handleSearch" inline>
        <el-form-item label="学生姓名">
          <el-input
            v-model="searchForm.studentName"
            placeholder="请输入学生姓名"
            clearable
            style="width: 150px"
          />
        </el-form-item>
        <el-form-item label="课程名称">
          <el-input
            v-model="searchForm.courseName"
            placeholder="请输入课程名称"
            clearable
            style="width: 150px"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="选择状态" clearable style="width: 120px">
            <el-option label="已选择" value="selected" />
            <el-option label="已完成" value="completed" />
            <el-option label="已退课" value="dropped" />
          </el-select>
        </el-form-item>
        <el-form-item label="选课时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :icon="Search">搜索</el-button>
          <el-button @click="handleReset" :icon="Refresh">重置</el-button>
          <el-button type="success" @click="handleExport" :icon="Download">导出记录</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计信息 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon total">
              <el-icon><Document /></el-icon>
            </div>
            <div class="stat-info">
              <h3>{{ stats.totalSelections }}</h3>
              <p>总选课数</p>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon active">
              <el-icon><CircleCheck /></el-icon>
            </div>
            <div class="stat-info">
              <h3>{{ stats.activeSelections }}</h3>
              <p>进行中</p>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon completed">
              <el-icon><Check /></el-icon>
            </div>
            <div class="stat-info">
              <h3>{{ stats.completedSelections }}</h3>
              <p>已完成</p>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon dropped">
              <el-icon><Close /></el-icon>
            </div>
            <div class="stat-info">
              <h3>{{ stats.droppedSelections }}</h3>
              <p>已退课</p>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 选课记录列表 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>选课记录</span>
          <div>
            <el-tag>共 {{ total }} 条记录</el-tag>
          </div>
        </div>
      </template>

      <el-table :data="selections" v-loading="loading">
        <el-table-column prop="student_id" label="学号" width="120" />
        <el-table-column prop="student_name" label="学生姓名" width="120" />
        <el-table-column prop="course_code" label="课程代码" width="120" />
        <el-table-column prop="course_name" label="课程名称" min-width="200" />
        <el-table-column prop="teacher_name" label="授课教师" width="120" />
        <el-table-column prop="credit" label="学分" width="80" align="center" />
        <el-table-column prop="selection_date" label="选课时间" width="150">
          <template #default="scope">
            {{ formatDate(scope.row.selection_date) }}
          </template>
        </el-table-column>
        <el-table-column prop="grade" label="成绩" width="100" align="center">
          <template #default="scope">
            <el-tag 
              v-if="scope.row.grade"
              :type="getGradeType(scope.row.grade)"
              size="small"
            >
              {{ scope.row.grade }}
            </el-tag>
            <span v-else class="no-grade">未录入</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="scope">
            <el-tag 
              :type="getStatusType(scope.row.status)"
              size="small"
            >
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click="handleViewDetail(scope.row)"
            >
              详情
            </el-button>
            <el-button
              v-if="scope.row.status === 'selected'"
              type="warning"
              size="small"
              @click="handleForceCancel(scope.row)"
            >
              强制退课
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.limit"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialog.visible"
      title="选课记录详情"
      width="600px"
    >
      <div v-if="detailDialog.record" class="selection-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="学号">
            {{ detailDialog.record.student_id }}
          </el-descriptions-item>
          <el-descriptions-item label="学生姓名">
            {{ detailDialog.record.student_name }}
          </el-descriptions-item>
          <el-descriptions-item label="课程代码">
            {{ detailDialog.record.course_code }}
          </el-descriptions-item>
          <el-descriptions-item label="课程名称">
            {{ detailDialog.record.course_name }}
          </el-descriptions-item>
          <el-descriptions-item label="授课教师">
            {{ detailDialog.record.teacher_name }}
          </el-descriptions-item>
          <el-descriptions-item label="学分">
            {{ detailDialog.record.credit }}
          </el-descriptions-item>
          <el-descriptions-item label="选课时间">
            {{ formatDate(detailDialog.record.selection_date) }}
          </el-descriptions-item>
          <el-descriptions-item label="当前成绩">
            <el-tag 
              v-if="detailDialog.record.grade"
              :type="getGradeType(detailDialog.record.grade)"
            >
              {{ detailDialog.record.grade }}
            </el-tag>
            <span v-else>未录入</span>
          </el-descriptions-item>
          <el-descriptions-item label="状态" :span="2">
            <el-tag :type="getStatusType(detailDialog.record.status)">
              {{ getStatusText(detailDialog.record.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item v-if="detailDialog.record.course_description" label="课程描述" :span="2">
            {{ detailDialog.record.course_description }}
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialog.visible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Search, 
  Refresh, 
  Download, 
  Document, 
  CircleCheck, 
  Check, 
  Close 
} from '@element-plus/icons-vue'
import { getAllSelections, dropCourse } from '@/api/selection'

const loading = ref(false)
const selections = ref([])
const total = ref(0)

const searchForm = reactive({
  studentName: '',
  courseName: '',
  status: '',
  dateRange: null
})

const pagination = reactive({
  page: 1,
  limit: 20
})

const detailDialog = reactive({
  visible: false,
  record: null
})

// 统计信息
const stats = computed(() => {
  const totalSelections = selections.value.length
  const activeSelections = selections.value.filter(s => s.status === 'selected').length
  const completedSelections = selections.value.filter(s => s.status === 'completed').length
  const droppedSelections = selections.value.filter(s => s.status === 'dropped').length

  return {
    totalSelections,
    activeSelections,
    completedSelections,
    droppedSelections
  }
})

// 获取成绩类型
const getGradeType = (grade) => {
  const score = parseFloat(grade)
  if (score >= 90) return 'success'
  if (score >= 80) return ''
  if (score >= 70) return 'warning'
  if (score >= 60) return 'info'
  return 'danger'
}

// 获取状态类型
const getStatusType = (status) => {
  switch (status) {
    case 'selected': return 'success'
    case 'completed': return 'info'
    case 'dropped': return 'danger'
    default: return ''
  }
}

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 'selected': return '进行中'
    case 'completed': return '已完成'
    case 'dropped': return '已退课'
    default: return '未知'
  }
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString()
}

// 获取选课记录列表
const fetchSelections = async () => {
  try {
    loading.value = true
    const params = {
      ...pagination,
      studentName: searchForm.studentName,
      courseName: searchForm.courseName,
      status: searchForm.status
    }
    
    // 处理日期范围
    if (searchForm.dateRange && searchForm.dateRange.length === 2) {
      params.startDate = searchForm.dateRange[0].toISOString().split('T')[0]
      params.endDate = searchForm.dateRange[1].toISOString().split('T')[0]
    }
    
    // 过滤空值
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key]
      }
    })

    const response = await getAllSelections(params)
    if (response.code === 0) {
      selections.value = response.data.selections
      total.value = response.data.total
    }
  } catch (error) {
    ElMessage.error('获取选课记录失败')
    console.error('获取选课记录失败:', error)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  fetchSelections()
}

// 重置搜索
const handleReset = () => {
  searchForm.studentName = ''
  searchForm.courseName = ''
  searchForm.status = ''
  searchForm.dateRange = null
  pagination.page = 1
  fetchSelections()
}

// 查看详情
const handleViewDetail = (record) => {
  detailDialog.record = record
  detailDialog.visible = true
}

// 强制退课
const handleForceCancel = async (record) => {
  try {
    await ElMessageBox.confirm(
      `确定要强制退选学生 "${record.student_name}" 的课程 "${record.course_name}" 吗？`,
      '强制退课',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const response = await dropCourse({ 
      courseId: record.course_id,
      studentId: record.student_id 
    })
    
    if (response.code === 0) {
      ElMessage.success('强制退课成功！')
      fetchSelections() // 重新获取列表
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('强制退课失败:', error)
    }
  }
}

// 导出记录
const handleExport = () => {
  ElMessage.info('导出功能开发中...')
}

// 分页处理
const handleSizeChange = () => {
  pagination.page = 1
  fetchSelections()
}

const handleCurrentChange = () => {
  fetchSelections()
}

onMounted(() => {
  fetchSelections()
})
</script>

<style scoped>
.selection-management {
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h1 {
  font-size: 28px;
  color: #303133;
  margin: 0 0 8px 0;
}

.page-header p {
  color: #909399;
  margin: 0;
}

.search-card {
  margin-bottom: 20px;
}

.stats-row {
  margin-bottom: 20px;
}

.stat-card {
  height: 100px;
}

.stat-content {
  display: flex;
  align-items: center;
  height: 100%;
}

.stat-icon {
  width: 50px;
  height: 50px;
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  font-size: 20px;
  color: white;
}

.stat-icon.total {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stat-icon.active {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stat-icon.completed {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.stat-icon.dropped {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.stat-info h3 {
  font-size: 24px;
  color: #303133;
  margin: 0 0 4px 0;
  font-weight: 600;
}

.stat-info p {
  color: #909399;
  margin: 0;
  font-size: 14px;
}

.table-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.no-grade {
  color: #c0c4cc;
  font-size: 12px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.selection-detail {
  padding: 10px 0;
}

:deep(.el-table) {
  font-size: 14px;
}

:deep(.el-descriptions__label) {
  font-weight: 600;
}
</style> 